package com.itheima.chapter07.array;

//二分查找
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int num = 4;
        int index = binarySearchForIndex(arr, num);
        System.out.println(index);
    }

    private static int binarySearchForIndex(int[] arr, int num) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = (left + right) >> 1;
            if (arr[mid] > num) {
                right = mid - 1;
            } else if (arr[mid] < num) {
                left = mid + 1;
            } else {
                return mid;
            }

        }
        return -1;


    }
}
